package com.zhongwang.mms.module.buy.service;

import com.zhongwang.mms.common.JsonResult;
import com.zhongwang.mms.gen.entity.BReportPlan;
import com.zhongwang.mms.gen.entity.BShoppingPlan;
import com.zhongwang.mms.gen.entity.POrderDetail;
import com.zhongwang.mms.gen.mapper.BShoppingPlanMapper;
import com.zhongwang.mms.module.buy.dao.BuyPlanDao;
import com.zhongwang.mms.module.buy.dao.ReportPlanDao;
import com.zhongwang.mms.module.buy.model.ShoppingPlanModel;
import com.zhongwang.mms.module.purchase.dao.PurPInventoryDao;
import com.zhongwang.mms.module.purchase.dao.PurPOrderDetailDao;
import com.zhongwang.mms.module.system.log.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Description: 外购件回货 Service
 * @Author: China.sgl
 * @Date: 2020/4/7 16:25
 */
@SuppressWarnings("ALL")
@Service
public class OuterReturnService {

    @Autowired
    private BuyPlanDao buyPlanDao;
    @Autowired
    private LogService logService;
    @Autowired
    private BShoppingPlanMapper shoppingPlanMapper;
    @Autowired
    private ReportPlanDao reportPlanDao;
    @Autowired
    private PurPOrderDetailDao purPOrderDetailDao;

    @Autowired
    private PurPInventoryDao purPInventoryDao;

    /**
     * 查询外购件回货列表
     *
     * @param shoppingPlanModel 条件
     * @return list
     */
    public List<ShoppingPlanModel> findOuterReturnList(ShoppingPlanModel shoppingPlanModel) {
        return buyPlanDao.findOuterReturnList(shoppingPlanModel);
    }

    /**
     * 确认回货
     * 获取单价回写到提报计划表 单价用于核算
     * @param sppId 采购计划ID
     * @param odaId 入库记录ID
     * @return 行数
     */
    @Transactional(rollbackFor = Exception.class)
    public int submitReturn(Integer sppId, Integer odaId) {
        BShoppingPlan plan = shoppingPlanMapper.selectByPrimaryKey(sppId);
        logService.saveLog("确认回货", "物料描述：" + plan.getSppMatDesc());
        plan.setSppOdaId(odaId);
        plan.setSppRetStatus(1);

        //确认回货条件提报计划总数等于采购计划总数即获取入库单单价，
        //否则单价为0，同时在采购计划单价和提报计划单价都记录单价，
        //提报计划还要记录SAP编码和物料描述
        //获取合报的提报计划列表
        List<BReportPlan> list = reportPlanDao.findBReportPlanBySppId(plan.getSppId());
        //获取提报计划总数
        Double totalNum = 0d;
        for (BReportPlan bReportPlan:list) {
            totalNum+=bReportPlan.getRppNum();
        }
        //如果采购数量等于提报计划总数
        if(plan.getSppNum().equals(totalNum)){
            POrderDetail pOrderDetail = purPOrderDetailDao.findOrderDetailByOdaId(odaId);
            //获取单价
            for (int i = 0; i < list.size() ; i++) {
                BReportPlan changeRppBuyPriceModel =  list.get(i);
                changeRppBuyPriceModel.setRppBuyPrice(pOrderDetail.getOdaNumPrice());
                changeRppBuyPriceModel.setRppConfirmReturnDate(new Date());
                reportPlanDao.updateBReportPlanRppBuyPriceAndRppConfirmReturnDateByRppId(changeRppBuyPriceModel);
                reportPlanDao.updateBReportPlanRppSapCodeAndRppBuyStockMatDesc(changeRppBuyPriceModel.getRppId(),pOrderDetail.getOdaSapCode(),pOrderDetail.getOdaMatDesc());
            }
            buyPlanDao.updateSppPrice(pOrderDetail.getOdaNumPrice(),sppId);
        }else {
            //获取单价
            for (int i = 0; i < list.size() ; i++) {
                BReportPlan changeRppBuyPriceModel =  list.get(i);
                changeRppBuyPriceModel.setRppBuyPrice(0d);
                changeRppBuyPriceModel.setRppConfirmReturnDate(new Date());
                reportPlanDao.updateBReportPlanRppBuyPriceAndRppConfirmReturnDateByRppId(changeRppBuyPriceModel);
            }
            buyPlanDao.updateSppPrice(0d,sppId);
        }
//        if (plan.getSppIntegraFlag() != null && plan.getSppIntegraFlag() == 1) {
//
////            if(list.size()>1){
////                BReportPlan bReportPlan = list.get(0);
////
////                boolean unitIsSame = true;
////                for (int i = 1; i < list.size() ; i++) {
////                    //合报的提报计划的单位不同，不可获取单价
////                    if (!bReportPlan.getRppUnit().equals(list.get(i).getRppUnit())){
////                        unitIsSame=false;
////                        break;
////                    }
////                    //确认回货的入库单单位与提报计划单位不同，不可获取单价
////                    if (!pOrderDetail.getOdaNumUnit().equals(list.get(i).getRppUnit())){
////                        unitIsSame=false;
////                        break;
////                    }
////                }
////                if(unitIsSame){
////                    for (int i = 0; i < list.size() ; i++) {
////                        BReportPlan changeRppBuyPriceModel =  list.get(0);
////                        changeRppBuyPriceModel.setRppBuyPrice(pOrderDetail.getOdaNumPrice());
////                        changeRppBuyPriceModel.setRppConfirmReturnDate(new Date());
////                        reportPlanDao.updateBReportPlanRppBuyPriceAndRppConfirmReturnDateByRppId(changeRppBuyPriceModel);
////                        reportPlanDao.updateBReportPlanRppSapCodeAndRppBuyStockMatDesc(changeRppBuyPriceModel.getRppId(),pOrderDetail.getOdaSapCode(),pOrderDetail.getOdaMatDesc());
////                    }
////                }
////            }
////        }
////        //如果不是合报
////        else if (plan.getSppIntegraFlag() != null || plan.getSppIntegraFlag() != 1) {
////           BReportPlan bReportPlan = reportPlanDao.getBReportPlanBySppId(plan.getSppId());
////            POrderDetail pOrderDetail = purPOrderDetailDao.findOrderDetailByOdaId(odaId);
////            //确认回货的入库单单位与提报计划单位相同，可获取单价
////            if (pOrderDetail.getOdaNumUnit().equals(bReportPlan.getRppUnit())){
////                bReportPlan.setRppBuyPrice(pOrderDetail.getOdaNumPrice());
////                bReportPlan.setRppConfirmReturnDate(new Date());
////                reportPlanDao.updateBReportPlanRppBuyPriceAndRppConfirmReturnDateByRppId(bReportPlan);
////                reportPlanDao.updateBReportPlanRppSapCodeAndRppBuyStockMatDesc(bReportPlan.getRppId(),pOrderDetail.getOdaSapCode(),pOrderDetail.getOdaMatDesc());
////            }
////        }
        return shoppingPlanMapper.updateByPrimaryKey(plan);
    }

    /**
     * 批量确认回货
     *
     * @param sppId 采购计划主键数组
     * @param odaId 入库记录主键数组
     * @return 行数
     */
    @Transactional(rollbackFor = Exception.class)
    public int submitReturn(Integer[] sppId, Integer[] odaId) {
        for (int i = 0; i < sppId.length; i++) {
            submitReturn(sppId[i], odaId[i]);
        }
        return 1;
    }

    /**
     * 撤消回货确认
     *
     * @param id 采购ID
     * @return 行数
     */
    @Transactional(rollbackFor = Exception.class)
    public int cancelRetrun(Integer id) {
        BShoppingPlan plan = shoppingPlanMapper.selectByPrimaryKey(id);
        List<BReportPlan> list = reportPlanDao.findBReportPlanBySppId(plan.getSppId());
        //获取单价
        for (int i = 0; i < list.size() ; i++) {
            BReportPlan changeRppBuyPriceModel =  list.get(i);
            changeRppBuyPriceModel.setRppBuyPrice(null);
            changeRppBuyPriceModel.setRppConfirmReturnDate(null);
            reportPlanDao.updateBReportPlanRppBuyPriceAndRppConfirmReturnDateByRppId(changeRppBuyPriceModel);
            reportPlanDao.updateBReportPlanRppSapCodeAndRppBuyStockMatDesc(changeRppBuyPriceModel.getRppId(),null,null);
        }
        buyPlanDao.updateSppPrice(null,id);
        logService.saveLog("撤消回货确认", "物料描述：" + plan.getSppMatDesc());
        plan.setSppOdaId(null);
        plan.setSppRetStatus(0);
        return shoppingPlanMapper.updateByPrimaryKey(plan);
    }

    /**
     * 预入库
     *
     * @param id 采购ID
     * @return 行数
     */
    public int pre(Integer id) {
        BShoppingPlan plan = shoppingPlanMapper.selectByPrimaryKey(id);
        logService.saveLog("预入库", "物料描述：" + plan.getSppMatDesc());
        plan.setSppPreStatus(1);
        plan.setSppPreDate(new Date());
        return shoppingPlanMapper.updateByPrimaryKey(plan);
    }

    /**
     * 批量预入库
     *
     * @param ids 采购计划主键数组
     * @return 行数
     */
    public int pre(Integer[] ids) {
        for (Integer id : ids) {
            pre(id);
        }
        return 1;
    }

    /**
     * 撤消预入库
     *
     * @param id 采购计划主键
     * @return 行数
     */
    public int cancelPre(Integer id) {
        BShoppingPlan plan = shoppingPlanMapper.selectByPrimaryKey(id);
        logService.saveLog("预入库", "物料描述：" + plan.getSppMatDesc());
        plan.setSppPreStatus(0);
        plan.setSppPreDate(null);
        return shoppingPlanMapper.updateByPrimaryKey(plan);
    }

    /**
     * 查询入库记录
     *
     * @param shoppingPlanModel 条件
     * @return list
     */
    public List<ShoppingPlanModel> findOrderDetail(ShoppingPlanModel shoppingPlanModel) {
        return buyPlanDao.findOrderDetail(shoppingPlanModel);
    }
    /**
     * checkProCodeAndTrackNo
     * 检测确认回货的入库信息的项目号和跟踪号与采购计划的项目号和跟踪号不同则提示
     * @param sppId
     * @param odaId
     * @return
     */
    public JsonResult checkProCodeAndTrackNo(Integer sppId, Integer odaId) {
        JsonResult jsonResult = new JsonResult();
        BShoppingPlan shoppingPlan =  buyPlanDao.getBShoppingPlanByPrimaryKey(sppId);
        POrderDetail pOrderDetail = purPOrderDetailDao.findOrderDetailByOdaId(odaId);
        if(shoppingPlan.getSppProjectCode().equals(pOrderDetail.getOdaProCode()) && shoppingPlan.getSppTrackCode().equals(pOrderDetail.getOdaTrackCode())){
            jsonResult.setType(JsonResult.ResultType.ERROR);
        }else if(!shoppingPlan.getSppProjectCode().equals(pOrderDetail.getOdaProCode()) && !shoppingPlan.getSppTrackCode().equals(pOrderDetail.getOdaTrackCode())){
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
            jsonResult.setMsg("您确认的入库单的项目号和跟踪号与采购计划不同，您确认要执行确认回货码？");
        }else if(!shoppingPlan.getSppProjectCode().equals(pOrderDetail.getOdaProCode())){
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
            jsonResult.setMsg("您确认的入库单的项目号与采购计划不同，您确认要执行确认回货码？");
        }else if(!shoppingPlan.getSppTrackCode().equals(pOrderDetail.getOdaTrackCode())){
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
            jsonResult.setMsg("您确认的入库单的跟踪号与采购计划不同，您确认要执行确认回货码？");
        }
        return jsonResult;
    }

    /**********************************************
     * @title: checkIsHaveBrand
     * @description: 检测采购计划中的提报计划是否有品牌
     * @param: []
     * @return: com.zhongwang.mms.common.JsonResult
     * @author: 徐一贺
     * @date: 2020/10/12 12:34
     * @versron: ver 1.0
     **********************************************
     */
    public JsonResult checkIsHaveBrand(Integer sppId) {
        JsonResult jsonResult = new JsonResult();
        jsonResult.setType(JsonResult.ResultType.SUCCESS);
        jsonResult.setData(0);
        List<BReportPlan> list = reportPlanDao.findBReportPlanBySppId(sppId);
        for (int i = 0; i < list.size(); i++) {
            if(list.get(i).getRppBrand()!=null && !"".equals(list.get(i).getRppBrand().trim())){
                jsonResult.setData(1);
                break;
            }
        }
        return jsonResult;
    }
}
